import ProductCommon from '@/api/ProductCommon';
import { createSharedHook, useReq } from '@/components';
import { get } from '@/utils/fp';
import { useMemo } from 'react';

const empty = {};
export function useWriteObjectHook() {
  const xhr = useReq(ProductCommon.costManager.getWriteObject);
  xhr.startOnce();
  return xhr.result?.data || empty;
}

export const useWriteObject = createSharedHook(useWriteObjectHook, empty);

const seal = (obj) => {
  Object.freeze(obj);
  Object.seal(obj);
  return obj;
};

export function useWriteObjectMapping() {
  const writeObject = useWriteObject() || empty;

  const alias = {
    ['保额']: 'coverage',
    ['保障期限']: 'protectionPeriod',
    ['年金领取时间']: 'pensionAge',
    ['岁数']: 'age',
    ['投保年龄']: 'age',
  };

  return useMemo(() => {
    let value = {};
    let isEmpty = true;
    Object.values(writeObject).forEach((list) => {
      list.forEach((item) => {
        isEmpty = false;
        const { costName, costObject, costCode } = item;
        const factorObject = `${costObject},${costName}`;
        value[costName] = factorObject;
        value[costCode] = factorObject;
      });
    });
    if (!isEmpty) {
      Object.entries(alias).forEach(([key, from]) => {
        value[key] = value[from];
      });
    }

    return seal(value);
  }, [writeObject]);
}

export const useSharedWriteObjectMapping = createSharedHook(useWriteObjectMapping, {});

export function useWriteObjectCascadeOptions() {
  const writeObject = useWriteObject() || empty;

  return useMemo(() => {
    return Object.entries(writeObject).map(([key, list]) => {
      const children = list.map((item) => ({
        value: item.costName,
        label: item.costName,
      }));
      return { value: key, label: key, children };
    });
  }, [writeObject]);
}

export function useWriteObjectOptions({ valueKey = 'costCode', labelKey = 'costName' } = {}) {
  const writeObject = useWriteObject() || empty;

  return useMemo(() => {
    return Object.entries(writeObject).flatMap(([key, list]) =>
      list.map((item) => ({
        value: get(valueKey)(item),
        label: get(labelKey)(item),
      })),
    );
  }, [writeObject]);
}

export const useSharedWriteObjectCas = createSharedHook(useWriteObjectCascadeOptions);
